package com.ittao.taopicturebackend.manager.cos;

import cn.hutool.core.io.FileUtil;
import com.ittao.taopicturebackend.config.CosClientConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Component
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;

    /**
     * 上传对象
     *
     * @param key  唯一键
     * @param file 文件
     */
    public void putObject(String key, File file) {
        // 创建一个PutObjectRequest对象，指定存储桶名称、对象键和文件路径
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        cosClient.putObject(putObjectRequest);
    }

    /**
     * 获取对象
     *
     * @param key 唯一键
     * @return
     */
    public COSObject getObject(String key) {
        // 获取存储桶中的对象
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
        return cosClient.getObject(getObjectRequest);
    }

    /**
     * 上传对象（附带图片信息）
     *
     * @param key  唯一键
     * @param file 文件
     * @return PutObjectResult 返回上传结果
     */
    public PutObjectResult putPictureObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        // 对图片进行处理（获取基本信息也作为一种图片的处理）
        PicOperations picOperations = new PicOperations();
        // 1. 获取图片的基本信息
        picOperations.setIsPicInfo(1);

        // 2. 图片加载优化策略（压缩、缩略图）
        List<PicOperations.Rule> rules = new ArrayList<>();
        // 2.1 图片压缩（转成 webp 格式）
        String webpKey = FileUtil.mainName(key) + ".webp";
        PicOperations.Rule compressRule = new PicOperations.Rule();
        // 适配 AI 扩图所需最小要求
        compressRule.setRule("imageMogr2/format/webp");
        compressRule.setBucket(cosClientConfig.getBucket());
        compressRule.setFileId(webpKey);
        rules.add(compressRule);

        // 2.2 缩略图处理（仅对 > 200 KB 的图片生成缩略图）
        if (file.length() > 20 * 1024) {
            PicOperations.Rule thumbnailRule = new PicOperations.Rule();
            thumbnailRule.setBucket(cosClientConfig.getBucket());
            String suffix = FileUtil.getSuffix(key);
            // 验证后缀是否为有效的图片格式，如果不是则使用png
            if (cn.hutool.core.util.StrUtil.isBlank(suffix) || !List.of("jpg", "jpeg", "png", "webp").contains(suffix.toLowerCase())) {
                suffix = "png";
            }
            String thumbnailKey = FileUtil.mainName(key) + "_thumbnail." + suffix;
            thumbnailRule.setFileId(thumbnailKey);
            // 缩放规则 /thumbnail/<Width>x<Height>>（如果大于原图宽高，则不处理）
            thumbnailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>", 128, 128));
            rules.add(thumbnailRule);
        }

        // 构造处理参数
        picOperations.setRules(rules);
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 删除对象
     *
     * @param key 唯一键
     */
    public void deleteObject(String key) {
        cosClient.deleteObject(cosClientConfig.getBucket(), key);
    }
}
